package com.qlm.config;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;

import org.apache.sanselan.formats.bmp.BmpImageParser;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriter;
import com.github.jaiimageio.impl.plugins.bmp.BMPImageWriterSpi;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jfinal.ext.interceptor.syslog.LogConfig;



public class BMPMaker {
	
	public static String name = "huangye";
	
	public static void main(String[] args) throws Exception {
		
		Map<String,String> map = new HashMap<String, String>();
		map.put("huangye", "皇爷");
		map.put("koukouxiang", "口口香");
		map.put("wuzizui", "伍子醉");
		map.put("pangge", "胖哥");
		map.put("bingzhilang", "宾之郎");
		map.put("xiangzuoji", "湘左记");
		map.put("hechang", "和畅");
		map.put("xiaolongwang", "小龙王");
		
		
		long start = System.currentTimeMillis();
		for(int j = 0;j<1 ;j++){
			startThread(j);
		}
		System.out.println(System.currentTimeMillis()-start);
	}
	
	private static void startThread(final int j) throws Exception {
		new Thread(new Runnable() {
			public void run() {
				int start = j * 1+600;
				for (int i = start; i < start+50; i++) {
				try {
					productQrcode(i+"");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			}
		}).start();;
	}

	static int width = 432,h = 216;
	
	public static void productQrcode(String id) throws Exception{
		 BufferedImage targetImg = new BufferedImage(width, h, BufferedImage.TYPE_INT_RGB);
//		 drawGraphic(targetImg);
		 Graphics2D g2d = targetImg.createGraphics();
//		  for (int x = 0; x < 600; x++) {  
//		       for (int y = 0; y < 300; y++) {  
//		    	   targetImg.setRGB(x, y, 16777215);  
//		       }  
//		     }  
		  BufferedImage drawGraphic1 = drawGraphic3();
		  File img = new File("E:\\img\\"+id+".bmp");
		  
		  if(!img.exists()){
			  img.createNewFile();
		  }
		  FileOutputStream out1 = new FileOutputStream(img);
		  ImageIO.write(drawGraphic1, "BMP", out1);
		  out1.close();
//		g2d.drawRect(500, 0, 200, 200);
		BufferedImage qrCode = qrCode("http://kww.qlima.vip/kww?"+id);
		g2d.drawImage(qrCode, null, 0, 0);
		g2d.drawImage(drawGraphic1, null, width/2, 0);
		g2d.dispose();
		File file = new File("E:\\qrcode\\"+id+".bmp");
		if(!file.exists()){
			file.createNewFile();
		}
		FileOutputStream out = new FileOutputStream(file);
		ImageIO.write(targetImg, "BMP", out);
//		 Iterator it = ImageIO.getImageWritersBySuffix("BMP");
//         if (it.hasNext()){
//		 ImageWriter iw = (ImageWriter) it.next();
//		  ImageOutputStream ios  =  ImageIO.createImageOutputStream(out);  
//		  iw.setOutput(ios);  
//		  IIOMetadata imageMetaData  =  iw.getDefaultImageMetadata(new ImageTypeSpecifier(targetImg), null);  
//             //new metadata  
//         Element tree  =  (Element) imageMetaData.getAsTree("javax_imageio_1.0");
//         int len = tree.getChildNodes().getLength();
//         NodeList childNodes = tree.getChildNodes();
//         for (int i = 0; i < len; i++) {
//        	 Node item = childNodes.item(i);
//        	 System.out.println(item.getNodeName());
//		}
//         Element jfif  =  (Element)tree.getElementsByTagName("Compression").item(0);  
//         jfif.setAttribute("Xdensity", Integer.toString(480) );  
//         jfif.setAttribute("Ydensity", Integer.toString(360));  
//         iw.write(imageMetaData, new IIOImage(targetImg, null, null), null);  
//         ios.close();
//         iw.dispose();  
//         }else{
//        	 System.out.println("无");
//         }
         
         
         
         out.close();
//		BmpWrite24 w = new BmpWrite24(600,300);
//		w.write(file);
	}
	
	/**
	 * 绘制图片
	 * @return
	 * @throws Exception
	 */
	private static BufferedImage drawGraphic2(String key) throws Exception{
		Random rand = new Random();
		int w = width/2;
	 BufferedImage image = null ;
		try {
			image = ImageIO.read(new File("E:\\sucai\\"+rand.nextInt(8)+".jpg"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(image != null){
	        Graphics2D g2 = image.createGraphics();
			drawShuiYin(w, g2,name);
			return image;
		}
		return image;
	}
	private static BufferedImage drawGraphic1(String key) throws Exception{
		Random rand = new Random();
			int w = width/2;
		 BufferedImage image = null ;
//			try {
//				image = ImageIO.read(new File("E:\\sucai\\"+rand.nextInt(8)+".jpg"));
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			if(image != null){
//		        Graphics2D g2 = image.createGraphics();
//				drawShuiYin(w, g2);
//				return image;
//			}
			image  = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	        Graphics2D g2 = image.createGraphics();
	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
	        Color[] colors = new Color[5];
	        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
	                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
	                Color.PINK, Color.YELLOW };
	        float[] fractions = new float[colors.length];
	        for(int i = 0; i < colors.length; i++){
	            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
	            fractions[i] = rand.nextFloat();
	        }
	        Arrays.sort(fractions);
	         
	        g2.setColor(Color.GRAY);// 设置边框色
	        g2.fillRect(0, 0, w, h);
	         
	        Color c = Color.white;
	        g2.setColor(c);// 设置背景色
	        g2.fillRect(0, 2, w, h-4);
	         
	        //绘制干扰线
	        Random random = new Random();
	        g2.setColor(Color.black);// 设置线条的颜色
	        for (int i = 0; i < 20; i++) {
	            int x = random.nextInt(w - 1);
	            int y = random.nextInt(h - 1);
	            int xl = random.nextInt(6) + 1;
	            int yl = random.nextInt(12) + 1;
	            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
	        }
	         
	        // 添加噪点
	        float yawpRate = 0.05f;// 噪声率
	        int area = (int) (yawpRate * w * h);
	        for (int i = 0; i < area; i++) {
	            int x = random.nextInt(w);
	            int y = random.nextInt(h);
	            int rgb = getRandomIntColor();
	            image.setRGB(x, y, rgb);
	        }
	         
	        shear(g2, w, h, c);// 使图片扭曲
	        int verifySize = 4;
//	        java.awt.GraphicsEnvironment eq = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
//	        Font[] allFonts = eq.getAllFonts();
//	        Font choose = null;
//	        for (Font font : allFonts) {
//	        	String family = font.getFamily();
//				System.out.println(font.getFamily());
//			}
	        drawShuiYin(w, g2);
	        String [] fontNames = {"hakuyoxingshu7000","宋体","楷体","叶根友毛笔行书2.0版","汉仪行楷简"};
	        String string = fontNames[random.nextInt(fontNames.length)];
	        char[] chars = VERIFY_CODES.toCharArray();
	        for(int i = 0; i < verifySize; i++){
        	   int fontSize = random.nextInt(10)+55;
        	   Font font = new Font(string, Font.PLAIN, fontSize);
	   	        g2.setFont(font);
	   	        g2.setColor(Color.black);
	            AffineTransform affine = new AffineTransform();
	            affine.setToRotation(Math.PI / 10 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
	            g2.setTransform(affine);
	            int index = random.nextInt(chars.length);
	            int left = 10;
//	            if(i == 0){
//	            	left = 20;
//	            }
//	            if(i == 1){
//	            	left = 75;
//	            }
//	            if(i == 2){
//	            	left = 135;
//	            }
	            left = ((w-10) / verifySize) * i + 5;
	            g2.drawChars(chars, index, 1,   left, random.nextInt(h-100)+50);
	        }
	        g2.dispose();
	        return image;
		}
	
	/**
	 * 绘制名称
	 * @return
	 * @throws Exception
	 */
	private static BufferedImage drawGraphic3(String key) throws Exception{
		Random rand = new Random();
			int w = width/2;
		 BufferedImage image = null ;
			image  = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	        Graphics2D g2 = image.createGraphics();
	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
	        Color[] colors = new Color[5];
	        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
	                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
	                Color.PINK, Color.YELLOW };
	        float[] fractions = new float[colors.length];
	        for(int i = 0; i < colors.length; i++){
	            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
	            fractions[i] = rand.nextFloat();
	        }
	        Arrays.sort(fractions);
	         
	        g2.setColor(Color.GRAY);// 设置边框色
	        g2.fillRect(0, 0, w, h);
	         
	        Color c = Color.white;
	        g2.setColor(c);// 设置背景色
	        g2.fillRect(0, 2, w, h-4);
	         
	        //绘制干扰线
	        Random random = new Random();
	        g2.setColor(Color.black);// 设置线条的颜色
	        for (int i = 0; i < 20; i++) {
	            int x = random.nextInt(w - 1);
	            int y = random.nextInt(h - 1);
	            int xl = random.nextInt(6) + 1;
	            int yl = random.nextInt(12) + 1;
	            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
	        }
	         
	        // 添加噪点
	        float yawpRate = 0.05f;// 噪声率
	        int area = (int) (yawpRate * w * h);
	        for (int i = 0; i < area; i++) {
	            int x = random.nextInt(w);
	            int y = random.nextInt(h);
	            int rgb = getRandomIntColor();
	            image.setRGB(x, y, rgb);
	        }
	         
	        shear(g2, w, h, c);// 使图片扭曲
	        int verifySize = VERIFY_CODES_NAmes.length();
	        drawShuiYin(w, g2);
	        String [] fontNames = {"hakuyoxingshu7000","宋体","楷体","叶根友毛笔行书2.0版","汉仪行楷简"};
	        String string = fontNames[random.nextInt(fontNames.length)];
	        char[] chars = VERIFY_CODES_NAmes.toCharArray();
	        for(int i = 0; i < verifySize; i++){
        	   int fontSize = random.nextInt(10)+55;
        	   Font font = new Font(string, Font.PLAIN, fontSize);
	   	        g2.setFont(font);
	   	        g2.setColor(Color.black);
	            AffineTransform affine = new AffineTransform();
	            affine.setToRotation(Math.PI / 10 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
	            g2.setTransform(affine);
	            int index = i;
	            int left = 10;
	            if(i == 0){
	            	left = 20;
	            }
	            if(i == 1){
	            	left = 75;
	            }
	            if(i == 2){
	            	left = 135;
	            }
//	            left = ((w-10) / verifySize) * i + 5;
	            g2.drawChars(chars, index, 1,   left, random.nextInt(h-100)+50);
	        }
	        g2.dispose();
	        return image;
		}

	private static void drawShuiYin(int w, Graphics2D g2,String name) throws IOException {
		BufferedImage read = ImageIO.read(new File(name+".JPG"));
			int height = 65;
			int width2 = 65;
			g2.drawImage(read, w-width2, h-height+5,height,height,null);
	}
	public static final String VERIFY_CODES = "1023456789ABCDEFGHJKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvbnm";
	public static final String VERIFY_CODES_NAmes = "口味王";
	public static void createQrcode(){
	}
	
	public static BufferedImage qrCode(String content) throws Exception{
		HashMap hints = new HashMap();
		// 内容所使用编码
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.MARGIN, 0);
		QrcodeConfig config = new QrcodeConfig();
		LogoConfig logoConfig = new LogoConfig();
//		config.setColor(0xFF6699);
		config.setHeight(h);
		config.setWidth(width/2);
		BitMatrix bitMatrix  = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,
				config.getWidth(), config.getHeight(), hints);;
		// 生成二维码
		
		 BufferedImage image = toBufferedImage(bitMatrix,config.getColor(), config.getBgColor());
		 FileInputStream is = new FileInputStream("kww.jpg");
		 try{
//			 drawLogo(image,new LogoConfig(),is);
		 }finally{
			 is.close();
		 }
		 return image;
	}
	
	private static void drawLogo(BufferedImage image,LogoConfig logoConfig,InputStream is) throws Exception{
		Graphics2D g = image.createGraphics();
		/**
		 * 读取Logo图片
		 */
//		BufferedImage logo = ImageIO.read(new FileInputStream(logoPath) );
		BufferedImage logo = ImageIO.read(is);
		/**
		 * 设置logo的大小,这里设置为二维码图片的20%,因为过大会盖掉二维码
		 */
		int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image
				.getWidth() * 2 / 10) : logo.getWidth(null), heightLogo = logo
				.getHeight(null) > image.getHeight() * 2 / 10 ? (image
				.getHeight() * 2 / 10) : logo.getWidth(null);

		// 计算图片放置位置
		/**
		 * logo放在中心
		 */
		 int x = (image.getWidth() - widthLogo) / 2;
		 int y = (image.getHeight() - heightLogo) / 2;
		/**
		 * logo放在右下角
		 */
//		int x = (image.getWidth() - widthLogo);
//		int y = (image.getHeight() - heightLogo);
		 
		// 开始绘制图片
		g.drawImage(logo, x, y, widthLogo, heightLogo, null);
		g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
		g.setStroke(new BasicStroke(logoConfig.getBorder()));
		g.setColor(logoConfig.getBorderColor());
		g.drawRect(x, y, widthLogo, heightLogo);

		g.dispose();
		logo.flush();
		image.flush();
	}
	
	 private static BufferedImage toBufferedImage(BitMatrix matrix, int color, int bgColor) {
		 int width = matrix.getWidth();  
	     int height = matrix.getHeight();  
	     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
	     for (int x = 0; x < width; x++) {  
	       for (int y = 0; y < height; y++) {  
	         image.setRGB(x, y, matrix.get(x, y) ? color : bgColor);  
	       }  
	     }  
	     return image;  
	}

	 private static Color getRandColor(int fc, int bc) {
		 Random random = new Random();
	        if (fc > 255)
	            fc = 255;
	        if (bc > 255)
	            bc = 255;
	        int r = fc + random.nextInt(bc - fc);
	        int g = fc + random.nextInt(bc - fc);
	        int b = fc + random.nextInt(bc - fc);
	        return new Color(r, g, b);
	    }
	     
	    private static int getRandomIntColor() {
	        int[] rgb =new int[]{0,0,0};
	        int color = 0;
	        for (int c : rgb) {
	            color = color << 8;
	            color = color | c;
	        }
	        return color;
	    }
	     
	    private static int[] getRandomRgb() {
	    	Random random = new Random();
	        int[] rgb = new int[3];
	        for (int i = 0; i < 3; i++) {
	            rgb[i] = random.nextInt(255);
	        }
	        return rgb;
	    }
	 
	    private static void shear(Graphics g, int w1, int h1, Color color) {
	        shearX(g, w1, h1, color);
	        shearY(g, w1, h1, color);
	    }
	     
	    private static void shearX(Graphics g, int w1, int h1, Color color) {
	    	Random random = new Random();
	        int period = random.nextInt(2);
	 
	        boolean borderGap = true;
	        int frames = 1;
	        int phase = random.nextInt(2);
	 
	        for (int i = 0; i < h1; i++) {
	            double d = (double) (period >> 1)
	                    * Math.sin((double) i / (double) period
	                            + (6.2831853071795862D * (double) phase)
	                            / (double) frames);
	            g.copyArea(0, i, w1, 1, (int) d, 0);
	            if (borderGap) {
	                g.setColor(color);
	                g.drawLine((int) d, i, 0, i);
	                g.drawLine((int) d + w1, i, w1, i);
	            }
	        }
	 
	    }
	 
	    private static void shearY(Graphics g, int w1, int h1, Color color) {
	    	Random random = new Random();
	        int period = random.nextInt(40) + 10; // 50;
	 
	        boolean borderGap = true;
	        int frames = 20;
	        int phase = 7;
	        for (int i = 0; i < w1; i++) {
	            double d = (double) (period >> 1)
	                    * Math.sin((double) i / (double) period
	                            + (6.2831853071795862D * (double) phase)
	                            / (double) frames);
	            g.copyArea(i, 0, 1, h1, 0, (int) d);
	            if (borderGap) {
	                g.setColor(color);
	                g.drawLine(i, (int) d, i, 0);
	                g.drawLine(i, (int) d + h1, i, h1);
	            }
	 
	        }
	 
	    }
	private static Color rectColor = new Color(0xf5f5f5);
	 
	 private static String drawGraphic(BufferedImage image){
		   // 获取图形上下文
		   Graphics g = image.createGraphics();
		   // 生成随机类
		   Random random = new Random();
		   // 设定背景色
		   g.setColor(getRandColor(200, 250));
		   g.fillRect(0, 0, 300, 300);
		   // 设定字体
		   g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

		   // 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		   g.setColor(getRandColor(160, 200));
		   for (int i = 0; i < 155; i++) {
		       int x = random.nextInt(300);
		       int y = random.nextInt(300);
		       int xl = random.nextInt(12);
		       int yl = random.nextInt(12);
		       g.drawLine(x, y, x + xl, y + yl);
		   }

		   // 取随机产生的认证码(img_randNumber位数字)
		   String sRand = "";
		   for (int i = 0; i < img_randNumber; i++) {
		       String rand = String.valueOf(strArr[random.nextInt(strArr.length)]);
		       sRand += rand;
		       // 将认证码显示到图象中
		       g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
		       // 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
		       g.drawString(rand, 20 * i + 14, 24);
		   }

		   // 图象生效
		   g.dispose();
		    
		   return sRand;
		}
//	 private static Color getRandColor(int fc, int bc) {
//		   Random random = new Random();
//		   if (fc > 255)
//		       fc = 255;
//		   if (bc > 255)
//		       bc = 255;
//		   int r = fc + random.nextInt(bc - fc);
//		   int g = fc + random.nextInt(bc - fc);
//		   int b = fc + random.nextInt(bc - fc);
//		   return new Color(r, g, b);
//		}
	 private static final String[] strArr = {"3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"};

private static int img_width = 85;
private static int img_height = 20;
private static int img_randNumber = 6;
	
}
